package rpc.registry;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import rpc.corder.MyObjectDecoder;
import rpc.corder.MyObjectEncoder;

/**
 * 注册中心主要功能就是负责将所有provider的服务名称和服务引用地址注册到一个容器中，并对外发布
 * （保存所有可用的服务名称和服务地址）
 */
public class RpcRegistry {

    private int port;

    public RpcRegistry(int port){
        this.port = port;
    }

    public void start(){
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,
                                    0,4,0,4));
                            pipeline.addLast(new LengthFieldPrepender(4));
                            //netty自带的ObjectEncoder和ObjectDecoder类实现对象序列化的传输
                            pipeline.addLast(new MyObjectEncoder());
                            pipeline.addLast(new MyObjectDecoder());
//                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE,
//                                    ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new RegistryHandler());

                        }
                    });
            b.childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = b.bind(port).sync();
            System.out.println("RPC Registry start listen at :" + port);
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new RpcRegistry(8888).start();
    }

}
